

//
//  QBEmoticonPackageModel.swift
//  04-表情键盘
//
//  Created by bing on 16/4/1.
//  Copyright © 2016年 bing. All rights reserved.
//

import UIKit

/// 表情包模型
class QBEmoticonPackageModel: NSObject {

    /// 表情包文件夹名称
    var id: String
    
    /// 表情包名称
    var group_name_cn: String
    
    /// 所有表情模型,
    var emoticons: [QBEmoticonModel] = [QBEmoticonModel]()
    
    /// 表情包所有页数据
    var pageEmoticons: [[QBEmoticonModel]] = [[QBEmoticonModel]]()
    
    /// 构造函数
    init(id: String, group_name_cn: String, emoticons: [QBEmoticonModel]) {
        self.id = id
        self.group_name_cn = group_name_cn
        self.emoticons = emoticons
        super.init()
        
        spliteEmoticons()
    }
    
    /// 将表情模型数组拆封成多页
    private func spliteEmoticons() {
        // 在构造函数的时候给属性赋值，不会调用didSet
        // 当别人给emoticons赋值，拆分成多页
        // 计算总页数：总个数 + 1页个数 - 1 / 1页个数
        let pageCount = (emoticons.count + QBEmoticonNumberOfPage - 1) / QBEmoticonNumberOfPage
        
        // 判断，如果一页都没有
        if pageCount == 0 {
            // 创建一页空的表情
            let emptyEmoticon = [QBEmoticonModel]()
            pageEmoticons.append(emptyEmoticon)
            return
        }
        
        // 遍历，拆分每一页
        for i in 0..<pageCount {
            
            let location = i * QBEmoticonNumberOfPage
            
            // 当最后一页截取的长度是否越界
            var length = QBEmoticonNumberOfPage
            
            if location + QBEmoticonNumberOfPage > emoticons.count {
                
                length = emoticons.count - location
            }
            
            let range = NSRange(location: location, length: length)
            
            // 一页表情
            let spliteEmoticons = (emoticons as NSArray).subarrayWithRange(range) as! [QBEmoticonModel]
            
            pageEmoticons.append(spliteEmoticons)
        }
    }
    
    override var description: String {
        
        return "\n\t表情包模型:id: \(id), group_name_cn: \(group_name_cn),emoticons:\(emoticons),pageEmoticons:\(pageEmoticons)"
    }
}
